package cn.android52.filepicker.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import by.kirich1409.viewbindingdelegate.viewBinding
import cn.android52.filepicker.R
import cn.android52.filepicker.databinding.FilePickerActivityBinding
import cn.android52.filepicker.ui.adapter.FileListAdapter
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.PathUtils
import java.io.File

class FilePickerActivity : AppCompatActivity(R.layout.file_picker_activity) {

    private val mBinding by viewBinding(FilePickerActivityBinding::bind)
    private val mFileListAdapter = FileListAdapter()
    private val mRootPath = PathUtils.getRootPathExternalFirst()
    private var mCurrentPath = mRootPath

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initData()
        initEvent()
    }

    private fun initView() {
        mBinding.apply {
            rvFileList.apply {
                adapter = mFileListAdapter
            }
        }
    }

    private fun initData() {
        enterFileDir(File(mCurrentPath))
    }

    private fun initEvent() {
        mFileListAdapter.setOnItemClickListener { v: View, item: File?, holder: FileListAdapter.InnerHolder, position: Int ->
            item?.let {
                enterFileDir(it)
            }
        }
    }

    private fun enterFileDir(file: File) {
        if (file.isDirectory) {
            mCurrentPath = file.path.orEmpty()
            val fileList = FileUtils.listFilesInDir(file)
            mFileListAdapter.resetData(fileList)
        }
    }

    override fun onBackPressed() {
        val currentFile = File(mCurrentPath)
        if (isRootDir(currentFile)) {
            // 已经是根目录了，直接返回
            finish()
            return
        }
        val parentFile = currentFile.parentFile
        // 如果上一级是目录，则进入上一级目录
        if (parentFile != null && parentFile.isDirectory) {
            mCurrentPath = parentFile.path
            enterFileDir(parentFile)
        }
    }

    private fun isRootDir(file: File) = ObjectUtils.equals(mRootPath, file.path)

    companion object {

        fun start(context: Context) {
            context.startActivity(Intent(context, FilePickerActivity::class.java))
        }
    }
}